package student.productions;

import java.util.Random;


/**
 * A representation of a critter rule.
 */
public class Rule extends AbstractNode {
	//invariant for children: contains exactly one Condition followed by exactly one Command

	/**
	 * Creates a new Rule
	 * @param cond This Rule's Condition
	 * @param cmd This Rule's Command
	 */
	public Rule(Condition cond, Command cmd){
		children.add(cond);
		children.add(cmd);
	}

	/**
	 * Returns toMutate with one mutation. 
	 * Effects: makes the mutation directly to toMutate
	 * @param toMutate the program to make the change to
	 * @param genome the program containing toMutate
	 * @return the mutated version of toMutate
	 * Requires: toMutate is a Rule
	 */
	public static AbstractNode mutate(AbstractNode toMutate, Program genome){
		Random rnd = new Random();
		int child = rnd.nextInt(2);
		if(child == 0)//mutating the condition
			toMutate.children.set(child, Condition.mutate(toMutate.children.get(child), genome));
		else //child == 1, mutating the command
			toMutate.children.set(child, Command.mutate(toMutate.children.get(child), genome));
		return toMutate;
	}

	@Override
	public void prettyPrint(StringBuffer sb) {
		children.get(0).prettyPrint(sb);
		sb.append("\n-->");
		children.get(1).prettyPrint(sb);
		sb.deleteCharAt(sb.length() - 1);//removes the space before the semicolon
		sb.append(";");
	}

	@Override
	public Node duplicate() {
		Condition condChild= (Condition)children.get(0).duplicate();
		Command cmdChild= (Command)children.get(1).duplicate();
		return new Rule(condChild, cmdChild);
	}

}
